﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Hu.Core.WebApi.Attributes
{
    public class HuActionAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        // 可添加自定义属性参数（如权限码）
        public string Permission { get; set; }

        public HuActionAttribute() { }
        public HuActionAttribute(string permission) { Permission = permission; }
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            // 1. 验证用户是否已认证
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                context.Result = new UnauthorizedResult();
                return;
            }
            // 2. 自定义权限验证逻辑（如检查权限码）
            if (!string.IsNullOrEmpty(Permission))
            {
                /*
                 * 可根据token验证的用户来进行判断是否有此权限码（Permission）
                 */
                var hasPermission = context.HttpContext.User.HasClaim(c =>
                    c.Type == "permissions" && c.Value == Permission);//此判断逻辑可以自定义

                if (!hasPermission)
                {
                    context.Result = new ForbidResult();
                    return;
                }
            }
        }
    }
}
